from rest_framework.generics import RetrieveAPIView, RetrieveUpdateDestroyAPIView, \
    GenericAPIView, CreateAPIView
from rest_framework.mixins import CreateModelMixin, ListModelMixin, UpdateModelMixin
from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.viewsets import GenericViewSet

from apps.hello.models import Hello, Essay
from apps.hello.serializers import HelloSerializer, EssaySerializer
from utils.message import Message


class HelloView(GenericAPIView, ListModelMixin, CreateModelMixin):
    """写 吾志  查看 吾志"""
    queryset = Hello.objects.all().order_by('-id')
    serializer_class = HelloSerializer

    def get(self, request):
        """获取所有吾志"""
        return self.list(request)

    def post(self, request):
        """写吾志"""
        return self.create(request)


class EssayView(RetrieveAPIView):
    """用户查看文章"""
    queryset = Essay.objects.all()
    serializer_class = EssaySerializer


class EssayAdminView(RetrieveUpdateDestroyAPIView):
    """后台管理查看 更新、 删除 文章"""
    permission_classes = (IsAdminUser,)
    queryset = Essay.objects.all()
    serializer_class = EssaySerializer


class ClickHelloView(GenericViewSet, UpdateModelMixin):
    """用户赞赏吾志, 用户只能点赞一次, 目前能点赞多次需要修改"""
    queryset = Hello.objects.all()
    serializer_class = HelloSerializer
    message = Message()

    def partial_update(self, request, *args, **kwargs):
        """重写path方法"""

        instance = self.get_object()
        praise = {'praise': instance.praise + 1}
        serializer = self.get_serializer(instance, data=praise, partial=True)
        serializer.is_valid(raise_exception=True)
        self.perform_update(serializer)
        return Response(self.message.success)


class WriteEssayView(CreateAPIView):
    """写文章"""
    serializer_class = EssaySerializer
    permission_classes = (IsAdminUser,)
